import { Component, Host, ChangeDetectorRef, Input, ViewChild } from "@angular/core";
import { AppComponent } from "../../../app.component";
import { Profile } from "../../../framework/login/models/profile.model";
import { StorageService } from "../../../shared/services/storage.service";
import { AuthenticationService } from "../../../framework/login/login.service";
import { BaseComponent } from "../../../shared/components/baseComponent/base.component";
import { SustainableProductsUtils, SustainableProductsCategory } from "./sustainableProductsUtils/sustainableProductsUtils";
import { ResearchSustainableProductsService } from "./researchSustainableProducts.service";
import { RangeOwnershipModel } from "../../../shared/models/rangeOwnership.model";
import { TableOptions } from "../../../shared/components/table/models/tableOptions.model";
import { SustainableProductsCompanyList } from "./sustainableProductsCompanyList/sustainableProductsCompanyList.component";
import { FilterSettingModel } from "../../../shared/components/landing-page-filter/models/filterSetting.model";
import { FilterSettingOptionModel } from "../../../shared/components/landing-page-filter/models/filterSettingOption.model";
import { Observable } from "rxjs";

@Component({
    templateUrl: 'researchSustainableProducts.component.html',
    styleUrls: ['../research.component.scss', 'researchSustainableProducts.component.scss'],
    providers: [ResearchSustainableProductsService]

})
export class ResearchSustainableProductsComponent extends BaseComponent {
    public showTutorial: boolean;
    public userInfo: Profile;
    public categories: SustainableProductsCategory[];
    public sustainableProductsUtils: SustainableProductsUtils = new SustainableProductsUtils();

    public settings: FilterSettingModel[] = [];
    private rangeOwnership: RangeOwnershipModel[] = [
        new RangeOwnershipModel("N/A", "N/A"),
        new RangeOwnershipModel("0-4.9%", "0-4.9%"),
        new RangeOwnershipModel("5-9.9%", "5-9.9%"),
        new RangeOwnershipModel("10-24.9%", "10-24.9%"),
        new RangeOwnershipModel("25-49.9%", "25-49.9%"),
        new RangeOwnershipModel("50-100%", "50-100%")
    ];
    private landingFilter: any;

    @ViewChild('list') list: SustainableProductsCompanyList;

    constructor(
        @Host() private rootComponent: AppComponent,
        private cdRef: ChangeDetectorRef,
        private authenticationService: AuthenticationService,
        private sustainableProductsService: ResearchSustainableProductsService) {
        super(cdRef);
    }

    ngOnInit() {
        this.categories = this.sustainableProductsUtils.getSustainableProductsCategories().filter(x => x.symbol != "AH");
        this.userInfo = StorageService.get().userInfo;
        this.showTutorial = this.userInfo.firstTimeSPUserAccepted ? !this.userInfo.firstTimeSPUserAccepted : true;

        Observable.forkJoin(
            this.sustainableProductsService.getIndicatorsList(),
            this.sustainableProductsService.getIndustriesList()).subscribe(data => {
                this.settings.push(new FilterSettingModel('indicators',
                    (data[0] as any[]).map((element, index) => { return new FilterSettingOptionModel(element.symbol, element.name, 'indicators', index) }),
                    'Sustainable Products Indicator',
                    'col-md-3',
                    (data[0] as any[]).length
                ));

                this.settings.push(new FilterSettingModel('subindustries',
                    (data[1] as any[]).map((element, index) => { return new FilterSettingOptionModel(element.id, element.name, 'subindustries', index) }),
                    'Industry',
                    'col-md-4',
                    (data[1] as any[]).length
                ));
                this.settings.push(new FilterSettingModel('rangeOwnerships',
                    this.rangeOwnership.map((element, index) => { return new FilterSettingOptionModel(element.id, element.name, 'rangeOwnerships', index) }),
                    'Range/Ownership',
                    'col-md-2'
                ));
            });

        this.rootComponent.finishLoading();
    }

    public toggleTutorial(): void {
        if (!this.userInfo.firstTimeSPUserAccepted) {
            this.authenticationService.acceptFirstTimeSPUser(this.userInfo.email).subscribe(_ => { });
            this.userInfo.firstTimeSPUserAccepted = true;
            StorageService.get().setProfile(this.userInfo);
        }
        this.showTutorial = !this.showTutorial;
    }

    public downloadFile(file) {
        window.open(file, '_blank');
    }

    public applyFilter(data: any) {
        this.landingFilter = data;
        let tableOptions = new TableOptions('companyName');
        tableOptions.filter = this.list.table.filter['companyName'] ? { companyName: this.list.table.filter['companyName'] } : this.list.table.filter;

        this.list.getBulkCompanies(this.updateTableOptions(data, tableOptions));
    }

    private updateTableOptions(landingFilter: any, tableOptions: TableOptions): TableOptions {
        if (landingFilter) {
            Object.keys(landingFilter).forEach(key => {
                tableOptions.filter[key] = landingFilter[key];
            });
        }
        return tableOptions;
    }

    public tableChanged(data: TableOptions) {
        this.list.getBulkCompanies(this.updateTableOptions(this.landingFilter, data));
    }
}